/**
 * MBR 管理模块
 */

const router = require('koa-router')()
const Mbr = require('./../models/mbrSchema')
const util = require('./../utils/util')

router.prefix('/mbrs')

// MBR 列表
router.get('/list', async (ctx) => {
    const { MBR_TYPE, MBR_NO, ID_CARD_NO } = ctx.request.query;
    const { page, skipIndex } = util.pager(ctx.request.query);
    let params = {}
    if (MBR_TYPE) params.MBR_TYPE = MBR_TYPE;
    if (MBR_NO) params.MBR_NO = MBR_NO;
    if (ID_CARD_NO) params.ID_CARD_NO = ID_CARD_NO;

    try {
        // 根据条件查询所有 MBR 列表
        const query = Mbr.find(params, { _id: 0 })
        const list = await query.skip(skipIndex).limit(page.pageSize)
        const total = await Mbr.countDocuments(params)

        ctx.body = util.success({
            page: {
                ...page,
                total
            },
            list
        })

    } catch (error) {
        ctx.body = util.fail(`查询异常:${error.stack}`)
    }
})

// 返回MBR总数
router.get('/count', async (ctx) => {
    try {
        const count = await Mbr.countDocuments()
        ctx.body = util.success({
            count
        })
    } catch (error) {        
        ctx.body = util.fail(`查询异常:${error.stack}`)        
    }
})  

module.exports = router    